import axios, { AxiosResponse } from "axios";
import Config from "../Config";
import Loading from "./loading";

export const host = Config.host;

const req = axios.create({
  baseURL: host + Config.baseUrl,
  timeout: 5000
})
//请求拦截
req.interceptors.request.use((config: any) => {
  const token = window.localStorage.getItem("token")
  if (token) {
    config.headers['authorization'] = token
  }
  Loading()
  return config
})
//响应拦截器
req.interceptors.response.use((response: AxiosResponse<any>) => {
  Loading.close();
  if (response.status === 200) {
    return response.data
  }
  if (response.status === 401) {
    window.localStorage.removeItem("token")
    window.localStorage.hash = "#/login"
    return
  }
  return Promise.reject(response.data)
}, (error: any) => {
  if (error.response.status === 401) {
    window.localStorage.removeItem("token")
    window.location.hash = "#/login"
    return Promise.reject(error.response.data)
  }
  return Promise.reject(error.response.data)
})
/**
 * 
 * @param {*} url //请求路径
 * @param {*} method //请求方法
 * @param {*} data //请求数据
 * @param {*} other //额外的信息，包括请求头设置或者是设置content-type
 */
export const request = async (props: {
  url: string,
  methods: 'GET' | 'POST' | 'PUT' | 'DELETE', data?: Object,
  headers?: Object,
  query?: Object
}):Promise<RequestRes> => {
  const {url,methods,query,data,headers} = props;
  let obj = {
    url:url,
    methods:methods,
    params:query,
    data:data,
    headers:headers,
  }
  var res = await req(obj)
  return res as any;
}
export default request
interface RequestRes{
  code:200|400|500|401,
  msg:string,
  data:any
}